<script setup lang="ts">
import {h} from 'vue';
import {Button, Dropdown, Menu, MenuItem, message, Modal as AntModal, Tag} from 'ant-design-vue';
import {Page} from '#/components/common-ui';
import {useDrawer, useModal, useVxeGrid} from '#/ui-kit';
import {useDictStore} from '#/stores';

import {findRoleListPage, removeRoleInfo} from '#/api/system/role';

import RoleChangeModal from './role-change-modal.vue';
import RoleAuthDrawerInject from "./role-auth-drawer.vue";
import RoleUserDrawerInject from "./role-user-drawer.vue";

const {getDictData} = useDictStore();

const [Grid, gridApi] = useVxeGrid({
  tableTitle: '角色列表',
  gridOptions: {
    columns: [
      {fixed: 'left', title: '#', type: 'seq', minWidth: 50},
      {field: 'name', title: '角色名称', minWidth: 120,},
      {field: 'code', title: '角色编码', minWidth: 120,},
      {field: 'sort', title: '排序', minWidth: 80,},
      {
        slots: {
          default: ({row}) => {
            const data = getDictData('enable_status', true).find((item) => item.value === row.enableStatus);
            return h(Tag, {color: data?.color || 'default'}, () => data?.label || '未知');
          }
        }, title: '启用状态', minWidth: 80,
      },
      {field: 'remark', title: '备注', minWidth: 180,},
      {field: 'createTime', title: '创建时间', formatter: 'formatDateTime', minWidth: 180,},
      {fixed: 'right', slots: {default: 'action'}, title: '操作', minWidth: 180},
    ],
    proxyConfig: {
      ajax: {
        query: async ({page}, formValues) => {
          return await getRoleListPage({
            pageNumber: page.currentPage,
            pageSize: page.pageSize,
            ...formValues
          });
        },
      }
    },
    stripe: true,
    keepSource: true,
    height: 'auto',
    toolbarConfig: {
      custom: true,
      refresh: true,
      zoom: true,
    },
  },
  formOptions: {
    commonConfig: {
      componentProps: {
        allowClear: true,
      }
    },
    schema: [
      {
        label: '角色名称',
        fieldName: 'name',
        component: 'Input',
        componentProps: {
          placeholder: '请输入角色名称',
        },
      },
      {
        label: '角色编码',
        fieldName: 'code',
        component: 'Input',
        componentProps: {
          placeholder: '请输入角色编码',
        },
      },
      {
        label: '启用状态',
        fieldName: 'enableStatus',
        component: 'Select',
        componentProps: {
          options: getDictData('enable_status', true),
          placeholder: '请选择启用状态',
        },
      },
    ],
    showCollapseButton: true,
    collapsed: true,
  }
});

const [Modal, modalApi] = useModal({
  class: 'w-[650px]',
  connectedComponent: RoleChangeModal,
});

const [RoleAuthDrawer, roleAuthDrawerApi] = useDrawer({
  title: '角色授权',
  class: 'w-[380px]',
  connectedComponent: RoleAuthDrawerInject,
});

const [RoleUserDrawer, roleUserDrawerApi] = useDrawer({
  title: '关联用户',
  class: 'w-[980px]',
  connectedComponent: RoleUserDrawerInject,
});

const getRoleListPage = (params) => {
  return new Promise<{ items: any; total: number }>((resolve) => {
    findRoleListPage(params).then(res => {
      resolve({
        items: res.records,
        total: res.totalRow,
      });
    }).catch(() => {
      resolve({
        items: [],
        total: 0,
      });
    })
  });
}

const handleCreateRole = () => {
  modalApi.setState({title: '新增角色'});
  modalApi.open();
}

const handleUpdateRole = (row) => {
  modalApi.setState({title: '更新角色'});
  modalApi.setData(row);
  modalApi.open();
}

const handleRemoveRole = (row) => {
  AntModal.confirm({
    title: '提示',
    content: '是否删除当前角色',
    centered: true,
    async onOk() {
      await removeRoleInfo(row.id).then(() => {
        gridApi.reload();
        message.success('角色删除成功');
      });
    }
  });
}

const handleAuthorization = (row) => {
  roleAuthDrawerApi.setData(row);
  roleAuthDrawerApi.open();
}

const handleRoleUser = (row) => {
  roleUserDrawerApi.setData(row);
  roleUserDrawerApi.open();
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <Button type="primary" v-access:code="['sys:role:create']" @click="handleCreateRole()">新增角色</Button>
      </template>
      <template #action="{row}">
        <Button type="link" size="small" v-access:code="['sys:role:update']" @click="handleUpdateRole(row)">编辑
        </Button>
        <Button type="link" size="small" v-access:code="['sys:role:remove']" @click="handleRemoveRole(row)">删除
        </Button>

        <Dropdown :trigger="['click']">
          <Button type="link" size="small" v-access:code="['sys:role:remove', 'sys:role:user-list-page']">更多</Button>
          <template #overlay>
            <Menu>
              <div v-access:code="['sys:role:authority']">
                <MenuItem @click="handleAuthorization(row)">角色授权</MenuItem>
              </div>
              <div v-access:code="['sys:role:user-list-page']">
                <MenuItem @click="handleRoleUser(row)">关联用户</MenuItem>
              </div>
            </Menu>
          </template>
        </Dropdown>
      </template>
    </Grid>

    <Modal @close="() => gridApi.reload()"/>

    <RoleAuthDrawer/>

    <RoleUserDrawer/>
  </Page>
</template>